﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using COSXML;
using COSXML.Auth;
using COSXML.Model.Object;
using COSXML.Model.Bucket;
using COSXML.CosException;
using COSXML.Model.Service;
using COSXML.Model.Tag;
using COSXML.Transfer;
using System.IO;
using COSSnippet;

namespace upload
{
    public partial class Tencent : Form
    {
        COSSnippet.ListObjectsModel l1 = new ListObjectsModel();
        string mainoffice = "医院文件/";//记录当前打开的文件夹，标记为所处位置，默认在医院文件
        public Tencent()
        {
            InitializeComponent();
            this.Width = 1000;//设置页面宽度为1000
            this.Height = 700;
            int buttonX = 40, buttonY = 0;//设置初始按钮的X轴和Y轴值
            //定义存储桶中文件夹和文件
            string[] table_office = l1.GetBucketWithDelimiter();
            string[] table_document = l1.GetBucketWithDelimiter2();

            //调用存储桶，获取存储桶中文件夹和文件名
            foreach (string office in table_office)//循环获得"医院文件"中的文件夹
            {
                string office1 = office.Substring(office.IndexOf("/")); // 
                string office2 = office1.Remove(0, 1);
                office1 = office2.Substring(0, office2.LastIndexOf("/"));

                //MessageBox.Show(office1);

                ButtonEx button11 = new ButtonEx(); //Button button11 = new Button();//动态添加button
                if (buttonX > (this.Width - 150))//如果botton的X值大于页面宽度，则X值重置，Y下移
                {
                    buttonX = 40;
                    buttonY += 100;
                    button11.Location = new Point(buttonX, buttonY);
                }
                else
                    button11.Location = new Point(buttonX, buttonY);
                button11.Image = upload.Properties.Resources.document;//将button的图片设置为文件夹
                button11.ImageAlign = ContentAlignment.TopCenter;//图片设置为button上方
                button11.Text = office1;//每个遍历一遍，获取科室名字
                button11.TextAlign = ContentAlignment.BottomCenter;//文件名设置为button下方
                button11.Size = new Size(120, 90);
                button11.FlatStyle = FlatStyle.Flat;
                button11.FlatAppearance.BorderSize = 0;
                this.MainPanel.Controls.Add(button11);
                office2 = office.Remove(0, 5);
                button11.DoubleClick += delegate (object sender, EventArgs e) { btn_DoubleClick(sender, e, office); };   //MouseDown += delegate (object sender1, EventArgs e1) { btn_DoubleClick(sender1, e1, office); };
                //MessageBox.Show(office2);
                //button11.Click += delegate
                //{
                //    ButtonClick(office);
                //};
                buttonX = buttonX + 150;
            }

            //将文件放在页面上
            foreach (string document in table_document)
            {
                string document1 = document;
                document1 = document1.Remove(0, 5);  // 取除前五个字符
                string Document_suffix = document1.Substring(document1.IndexOf("."));
                //MessageBox.Show(Document_suffix);
                Button button11 = new Button();
                if (buttonX > this.Width - 150)
                {
                    buttonX = 40;
                    buttonY += 100;
                    button11.Location = new Point(buttonX, buttonY);
                }
                else
                    button11.Location = new Point(buttonX, buttonY);
                switch (Document_suffix)
                {
                    case ".jpg":
                        button11.Image = Properties.Resources.jpg;
                        break;
                    case ".xlsx":
                        button11.Image = Properties.Resources.xlsx__1_;
                        break;
                    case ".xls":
                        button11.Image = Properties.Resources.xlsx__1_;
                        break;
                    case ".pdf":
                        button11.Image = Properties.Resources.pdf__1_;
                        break;
                    case ".pptx":
                        button11.Image = Properties.Resources.pptx;
                        break;
                    case ".ppt":
                        button11.Image = Properties.Resources.pptx;
                        break;
                    case ".doc":
                        button11.Image = Properties.Resources.docx__1_;
                        break;
                    case ".docx":
                        button11.Image = Properties.Resources.docx__1_;
                        break;

                }
                button11.ImageAlign = ContentAlignment.TopCenter;
                button11.Text = document1;
                button11.TextAlign = ContentAlignment.BottomCenter;
                button11.Size = new Size(117, 88);
                button11.FlatStyle = FlatStyle.Flat;
                button11.FlatAppearance.BorderSize = 0;
                this.MainPanel.Controls.Add(button11);
                //button11.Click += delegate
                //{

                //    //ButtonClick();
                //};
                button11.MouseDown += delegate (object sender, MouseEventArgs e) { btn_MouseDown(sender, e, document, button11); };   //MouseDown += delegate (object sender1, EventArgs e1) { btn_DoubleClick(sender1, e1, office); };


                buttonX = buttonX + 150;
                label1.Text = mainoffice;

            }
        }
        private void Tencent_Load(object sender, EventArgs e)
        {
            
        }

        //上传文件
        private void button2_Click(object sender, EventArgs e)
        {
            
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.InitialDirectory = Application.StartupPath; //设置打开对话框的初始目录，默认目录为exe运行文件所在的路径
            ofd.RestoreDirectory = true;
            ofd.Title = "请选择要打开的文件";//设置打开对话框的标题
            ofd.Multiselect = true;//设置打开对话框可以多选
            ofd.Filter = "所有文件|*.*";//设置对话框打开的文件类型
            ofd.FilterIndex = 2; //设置文件对话框当前选定的筛选器的索引.
            ofd.RestoreDirectory = true;//设置对话框是否记忆之前打开的目录
            if (ofd.ShowDialog() == DialogResult.OK)//打开文件选择框
            {
                string filePath = ofd.FileName;//获取用户选择的文件完整路径
                var fileInfo = new FileInfo(filePath);
                string fileName = fileInfo.Name;
                Upload_Document(filePath, fileName);
            }
        }
        private async void Upload_Document(string path, string filename)
        {
            //string appid = "1317383760";//设置腾讯云账户的账户标识 APPID
            string region = "ap-shanghai"; //设置一个默认的存储桶地域
            CosXmlConfig config = new CosXmlConfig.Builder()
              .IsHttps(true)  //设置默认 HTTPS 请求
              .SetRegion(region)  //设置一个默认的存储桶地域
              .SetDebugLog(true)  //显示日志
              .Build();  //创建 CosXmlConfig 对象

            string secretId = ("AKIDNf2PoDQfjgaHtJZI2mLhoi1eEeuAF9sP"); //用户的 SecretId，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
            string secretKey = ("Yv8A1iFbnphNJ4eQOEzkGex6CC5qOhkW"); //用户的 SecretKey，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
            long durationSecond = 600;  //每次请求签名有效时长，单位为秒
            QCloudCredentialProvider cosCredentialProvider = new DefaultQCloudCredentialProvider(secretId, secretKey, durationSecond);

            //初始化 CosXmlServer
            CosXml cosXml = new CosXmlServer(config, cosCredentialProvider);
            // 初始化 TransferConfig
            TransferConfig transferConfig = new TransferConfig();

            // 初始化 TransferManager
            TransferManager transferManager = new TransferManager(cosXml, transferConfig);

            String bucket = "document-manage-1317383760"; //存储桶，格式：BucketName-APPID
            String cosPath = "医院文件/" + filename; //对象在存储桶中的位置标识符，即称对象键
            String srcPath = @path;//本地文件绝对路径
            string Document_suffix = filename.Substring(filename.IndexOf("."));
            MessageBox.Show(Document_suffix);
            // 上传对象
            COSXMLUploadTask uploadTask = new COSXMLUploadTask(bucket, cosPath);
            uploadTask.SetSrcPath(srcPath);

            uploadTask.progressCallback = delegate (long completed, long total)
            {
                Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total));
            };

            try
            {
                COSXML.Transfer.COSXMLUploadTask.UploadTaskResult result = await transferManager.UploadAsync(uploadTask);
                Console.WriteLine(result.GetResultInfo());
                string eTag = result.eTag;
            }
            catch (Exception e)
            {
                Console.WriteLine("CosException: " + e);
            }
            //return i;
        }
        //下载文件
        private void button3_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "全部文件(*.*)|*.*";
            sfd.RestoreDirectory = true;
            string filename= "", filepath = "";
            if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //try
                {
                    string saveFileName = sfd.FileName;
                    string localFilePath;
                    //FileStream fs = new FileStream(saveFileName, FileMode.OpenOrCreate, FileAccess.Write);
                    //获得文件路径 
                    localFilePath = sfd.FileName.ToString();
                    //获取文件名，不带路径 
                    filename= localFilePath.Substring(localFilePath.LastIndexOf("\\") + 1);

                    //获取文件路径，不带文件名 
                    filepath = localFilePath.Substring(0, localFilePath.LastIndexOf("\\"));
                }
            }
            COSSnippet.Download d1 = new Download();
            //d1.DDownload(filename, filepath);
        }


        private void TurnForm2_Click(object sender, EventArgs e)
        {
            Form2 f2 = new Form2();
            this.Hide();
            f2.Show();
        }
        /// <summary>
        /// 使用timer的双击事件
        private void Double_Click_Click(object sender, EventArgs e)
        {
                if (timer1.Enabled)
                {
                    timer1.Enabled = false;
                //以下为双击事件内容
                     MessageBox.Show("Hello");
                    //双击事件结束
                }
                else
                {
                    timer1.Enabled = true;
                }
        }
        void ButtonClick(string office)
        {
            if (timer1.Enabled)
            {
                timer1.Enabled = false;
                //以下为双击事件内容
                MainPanel.Controls.Clear();
                //string [] document= l1.GetBucketWithDelimiter_document(office);
                load(office);
                label1.Text = office;
                //双击事件结束
            }
            else
            {
                timer1.Enabled = true;
            }
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (timer1.Tag == null)
            {
                timer1.Tag = DateTime.Now.ToString();
            }
            else
            {
                if ((DateTime.Now - Convert.ToDateTime(timer1.Tag)).TotalSeconds > 0.5)
                {
                    timer1.Tag = null;
                    timer1.Enabled = false;
                    ////以下为单击事件内容
                    //MessageBox.Show("timer");
                    ////单击事件结束
                }
            }
        }

        /// </summary>

        //新建双击
        public class ButtonEx : Button
        {
            public new event EventHandler DoubleClick;
            DateTime clickTime;
            bool isClicked = false;
            protected override void OnClick(EventArgs e)
            {
                base.OnClick(e);
                if (isClicked)
                {
                    TimeSpan span = DateTime.Now - clickTime;
                    if (span.Milliseconds < SystemInformation.DoubleClickTime - 200)
                    {
                        DoubleClick(this, e);
                        isClicked = false;
                    }
                    else
                    {
                        isClicked = true;
                        clickTime = DateTime.Now;
                    }
                }
                else
                {
                    isClicked = true;
                    clickTime = DateTime.Now;
                }
            }
        }

        void btn_DoubleClick(object sender, EventArgs e, string office)
        {
            MainPanel.Controls.Clear();
            //string [] document= l1.GetBucketWithDelimiter_document(office);
            load(office);
            label1.Text = office;
        }



        void btn_MouseDown(object sender, MouseEventArgs e, string document, Button btn)
        {
            if (e.Button == MouseButtons.Left && e.Clicks == 1)
            {
            }
            else if (e.Button == MouseButtons.Right && e.Clicks == 1)
            {
                string document1 = document.Remove(0, document.LastIndexOf("/") + 1);// 只保留文件名
                string Document_suffix = document1.Substring(document1.IndexOf("."));
                ContextMenu m1 = new ContextMenu();
                m1.MenuItems.Add("下载");
                //m1.MenuItems.Add("添加图片");
                m1.Show(btn, new Point(e.X, e.Y));
                m1.MenuItems[0].Click += delegate
                {
                    SaveFileDialog sfd = new SaveFileDialog();
                    switch (Document_suffix)
                    {
                        case ".jpg":
                            sfd.Filter = "(*.jpg)|*.jpg";
                            break;
                        case ".xlsx":
                            sfd.Filter = "(*.xlxs)|*.xlxs"; break;
                        case ".xls":
                            sfd.Filter = "(*.xls)|*.xls"; break;
                        case ".pdf":
                            sfd.Filter = "(*.pdf)|*.pdf"; break;
                        case ".pptx":
                            sfd.Filter = "(*.pptx)|*.pptx"; break;
                        case ".ppt":
                            sfd.Filter = "(*.ppt)|*.ppt"; break;
                        case ".doc":
                            sfd.Filter = "(*.doc)|*.doc"; break;
                        case ".docx":
                            sfd.Filter = "(*.docx)|*.docx"; break;
                        case ".txt":
                            sfd.Filter = "(*.txt)|*.txt"; break;
                    }
                    //sfd.Filter = "文本文件(*.txt)|*.txt";
                    sfd.FileName = document1;
                    sfd.RestoreDirectory = true;
                    sfd.AddExtension = true;
                    string filename = "", filepath = "";
                    if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        //try
                        {
                            string saveFileName = sfd.FileName;
                            string localFilePath;
                            //FileStream fs = new FileStream(saveFileName, FileMode.OpenOrCreate, FileAccess.Write);
                            //获得文件路径 
                            localFilePath = sfd.FileName.ToString();
                            //获取下载之后文件名，不带路径 
                            filename = localFilePath.Substring(localFilePath.LastIndexOf("\\") + 1);

                            //获取文件路径，不带文件名 
                            filepath = localFilePath.Substring(0, localFilePath.LastIndexOf("\\"));
                        }
                    }
                    COSSnippet.Download d1 = new Download();
                    d1.DDownload(filename, filepath,document);
                };
                //m1.MenuItems[1].Click += delegate
                //{
                //    MessageBox.Show("++++");
                //};

            }
        }

        private void button1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && e.Clicks == 1)
            {
            }
            else if (e.Button == MouseButtons.Right && e.Clicks == 1)
            {
                ContextMenu m1 = new ContextMenu();
                m1.MenuItems.Add("删除图片");
                m1.MenuItems.Add("添加图片");
                m1.Show(button1, new Point(e.X, e.Y));
                m1.MenuItems[0].Click += delegate
                {
                    MessageBox.Show("----");
                };
                m1.MenuItems[1].Click += delegate
                {
                    MessageBox.Show("++++");
                };

            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (label1.Text.Trim() == "医院文件/")
            {
            }
            else
            {
                MainPanel.Controls.Clear();
                string office = label1.Text.Remove(label1.Text.LastIndexOf("/"));
                string office2 = office.Remove(office.LastIndexOf("/") + 1);
                label1.Text = office2;
                load(office2);
            }
        }

        //在form页面上生成文件
        void load_document(string mainoffice)
        {
            int buttonX = 40, buttonY = 0;
            string[] table_document = l1.GetBucketWithDelimiter_office(mainoffice);
            foreach (string document in table_document)
            {
                string document1 = document;

                document1 = document1.Remove(0, 5);  // 取除前五个字符
                string Document_suffix = document1.Substring(document1.IndexOf("."));
                //MessageBox.Show(Document_suffix);
                Button button11 = new Button();
                if (buttonX > this.Width - 150)
                {
                    buttonX = 40;
                    buttonY += 100;
                    button11.Location = new Point(buttonX, buttonY);
                }
                else
                    button11.Location = new Point(buttonX, buttonY);
                switch (Document_suffix)
                {
                    case ".jpg":
                        button11.Image = Properties.Resources.jpg;
                        break;
                    case ".xlsx":
                        button11.Image = Properties.Resources.xlsx__1_;
                        break;
                    case ".xls":
                        button11.Image = Properties.Resources.xlsx__1_;
                        break;
                    case ".pdf":
                        button11.Image = Properties.Resources.pdf__1_;
                        break;
                    case ".pptx":
                        button11.Image = Properties.Resources.pptx;
                        break;
                    case ".ppt":
                        button11.Image = Properties.Resources.pptx;
                        break;
                    case ".doc":
                        button11.Image = Properties.Resources.docx__1_;
                        break;
                    case ".docx":
                        button11.Image = Properties.Resources.docx__1_;
                        break;

                }
                //button11.Image = upload.Properties.Resources.document;
                button11.ImageAlign = ContentAlignment.TopCenter;
                button11.Text = document1;
                button11.TextAlign = ContentAlignment.BottomCenter;
                button11.Size = new Size(117, 88);
                this.MainPanel.Controls.Add(button11);
                button11.Click += delegate
                {

                    //ButtonClick();
                };
                buttonX = buttonX + 150;
            }
        }

        //在页面生成文件夹
        
        void load(string mainoffice)
        {
            int buttonX = 40, buttonY = 0;//设置初始按钮的X轴和Y轴值
            //定义存储桶中文件夹和文件
            string[] table_office = l1.GetBucketWithDelimiter_office(mainoffice);
            string[] table_document = l1.GetBucketWithDelimiter_document(mainoffice);

            //调用存储桶，获取存储桶中文件夹和文件名
                foreach (string office in table_office)//循环获得存储桶中各个科室的文件夹
            {
                string office1 = office.Remove(office.LastIndexOf("/"));
                office1 = office1.Remove(0, office1.LastIndexOf("/") + 1);
                //string office1 = office.Substring(office.IndexOf("/")); // 
                //string office2 = office1.Remove(0, 1);
                //office1 = office2.Substring(0, office2.LastIndexOf("/"));

                //MessageBox.Show(office1);

                ButtonEx button11 = new ButtonEx(); //Button button11 = new Button();//动态添加button
                if (buttonX > (this.Width - 150))//如果botton的X值大于页面宽度，则X值重置，Y下移
                {
                    buttonX = 40;
                    buttonY += 100;
                    button11.Location = new Point(buttonX, buttonY);
                }
                else
                    button11.Location = new Point(buttonX, buttonY);
                button11.Image = upload.Properties.Resources.document;//将button的图片设置为文件夹
                button11.ImageAlign = ContentAlignment.TopCenter;//图片设置为button上方
                button11.Text = office1;//每个遍历一遍，获取科室名字
                button11.TextAlign = ContentAlignment.BottomCenter;//文件名设置为button下方
                button11.Size = new Size(120, 90);
                button11.FlatStyle = FlatStyle.Flat;
                button11.FlatAppearance.BorderSize = 0;
                this.MainPanel.Controls.Add(button11);
                //office2 = office.Remove(0, 5);
                //mainoffice =office1;
                //MessageBox.Show(office2);

                button11.DoubleClick += delegate (object sender, EventArgs e) { btn_DoubleClick( sender, e, office); };   //MouseDown += delegate (object sender1, EventArgs e1) { btn_DoubleClick(sender1, e1, office); };

                //button11.Click += delegate
                //{
                //    ButtonClick(office);
                //};
                buttonX = buttonX + 150;
            }

            //将文件放在页面上
                foreach (string document in table_document)
            {
                //document1 = document;
                string document1 = document.Remove(0, document.LastIndexOf("/") + 1);// 只保留文件名
                string Document_suffix = document1.Substring(document1.IndexOf("."));
                //MessageBox.Show(Document_suffix);
                Button button11 = new Button();
                if (buttonX > this.Width - 150)
                {
                    buttonX = 40;
                    buttonY += 100;
                    button11.Location = new Point(buttonX, buttonY);
                }
                else
                    button11.Location = new Point(buttonX, buttonY);
                switch (Document_suffix)
                {
                    case ".jpg":
                        button11.Image = Properties.Resources.jpg;
                        break;
                    case ".xlsx":
                        button11.Image = Properties.Resources.xlsx__1_;
                        break;
                    case ".xls":
                        button11.Image = Properties.Resources.xlsx__1_;
                        break;
                    case ".pdf":
                        button11.Image = Properties.Resources.pdf__1_;
                        break;
                    case ".pptx":
                        button11.Image = Properties.Resources.pptx;
                        break;
                    case ".ppt":
                        button11.Image = Properties.Resources.pptx;
                        break;
                    case ".doc":
                        button11.Image = Properties.Resources.docx__1_;
                        break;
                    case ".docx":
                        button11.Image = Properties.Resources.docx__1_;
                        break;

                }
                button11.ImageAlign = ContentAlignment.TopCenter;
                button11.Text = document1;
                button11.TextAlign = ContentAlignment.BottomCenter;
                button11.Size = new Size(117, 88);
                button11.FlatStyle = FlatStyle.Flat;
                button11.FlatAppearance.BorderSize = 0;
                this.MainPanel.Controls.Add(button11);
                button11.Click += delegate
                {

                    //ButtonClick();
                };
                //button11.MouseDown += new MouseEventHandler(MouseDown);
                button11.MouseDown += delegate (object sender, MouseEventArgs e) { btn_MouseDown(sender, e, document, button11); };   //MouseDown += delegate (object sender1, EventArgs e1) { btn_DoubleClick(sender1, e1, office); };
                buttonX = buttonX + 150;

            }
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }
    }
}
